package com.hctforgreen.greenservice;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.hctforgreen.greenservice.ctr.DbController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.db.DBFeedbackInfoManager;
import com.hctforgreen.greenservice.model.FeedBackListEntity.FeedBackEntity;
import com.hctforgreen.greenservice.model.PhotoEntity;
import com.hctforgreen.greenservice.model.ResultEntity;
import com.hctforgreen.greenservice.model.SerieListEntity.SerieEntity;
import com.hctforgreen.greenservice.model.VideoEntity;
import com.hctforgreen.greenservice.ui.adapter.SinglePicListAdapter;
import com.hctforgreen.greenservice.ui.adapter.SingleVideoListAdapter;
import com.hctforgreen.greenservice.ui.adapter.SpinnerStringsAdapter;
import com.hctforgreen.greenservice.ui.widget.DefaultSeriesListPopupView;
import com.hctforgreen.greenservice.ui.widget.GridViewIsChildOfScrollView;
import com.hctforgreen.greenservice.utils.BitmapUtil;
import com.hctforgreen.greenservice.utils.FileCacheUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.KeyboardUtil;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;
import com.hctforgreen.greenservice.utils.Utils;
import com.umeng.analytics.MobclickAgent;

/**
 * 提交竞品资料V3
 * 
 * @author Tallen Zhai
 * 
 */
public class SubmitCompetingActivity extends SubmitFeedBackActivityV3 {
	private final static int FILE_SELECT_CODE = 0x113;

	private List<PhotoEntity> picList = new ArrayList();
	private SinglePicListAdapter mAdapter;

	private List<VideoEntity> videoList = new ArrayList();
	private SingleVideoListAdapter mVideoAdapter;

	/**
	 * 相册
	 */
	public final int PHOTO_PICKED_WITH_DATA = 1;
	public final int VIDEO_PICKED_WITH_DATA = 2;
	public final int FROM_HISTORY = 3;
	private SubmitCompetingActivity mSelf;

	public FeedBackEntity backEntity;//

	private File uploadFile;// 新增上传文件

	// private String applianceType = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_submit_competing);
		mSelf = this;
		initSkinLayout();
		initClickEdgehideKeyboard();
		initTitleButtonBar();
		initWindow();
		initByFeedback();
		initSubmitBtn();
	}

	/**
	 * 点击边缘隐藏输入法
	 */
	private void initClickEdgehideKeyboard() {
		LinearLayout rootLyt = (LinearLayout) findViewById(R.id.lyt_root);
		rootLyt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				KeyboardUtil keyboardUtil = new KeyboardUtil();
				keyboardUtil.hideSoftKeyboard(v);
			}
		});
	}

	private void initSubmitBtn() {
		final EditText brand_edit = (EditText) findViewById(R.id.brand_edit);
		final EditText topic_edit = (EditText) findViewById(R.id.title_edit);
		final EditText content_edit = (EditText) findViewById(R.id.content_edit);
		final Button submitBtn = (Button) findViewById(R.id.sub_btn);
		submitBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String personId = LoginResultStoreUtil
						.get(SubmitCompetingActivity.this).personId;
				String brand = brand_edit.getText().toString();
				String topic = topic_edit.getText().toString().trim();
				String content = content_edit.getText().toString().trim();

				if (brand.equals("")) {
					Toast.makeText(SubmitCompetingActivity.this,
							R.string.competing_brand_hint, Toast.LENGTH_SHORT)
							.show();
					return;
				}

				if (topic.equals("")) {
					Toast.makeText(SubmitCompetingActivity.this,
							R.string.submit_feed_topic_input_not_null_hint,
							Toast.LENGTH_SHORT).show();
					return;
				}

				if (content.equals("")) {
					Toast.makeText(SubmitCompetingActivity.this,
							R.string.submit_feed_content_input_not_null_hint,
							Toast.LENGTH_SHORT).show();
					return;
				}

				List<String> pathList = new ArrayList<String>();
				for (PhotoEntity entity : picList) {
					if (!entity.path.equals("")) {
						pathList.add(entity.path);
					}
				}

				List<String> videoPathes = new ArrayList<String>();
				for (VideoEntity entity : videoList) {
					if (!entity.path.equals("")) {
						videoPathes.add(entity.path);
					}
				}
				sub_text(submitBtn, personId, brand, topic, content, pathList,
						videoPathes);

			}
		});
	}

	private void initWindow() {
		View convertView = findViewById(R.id.lyt_parent);
		// initApplianceSpinner();
		// initFeedbackTypeSpinner();
		initSelectFileLayout(convertView);
		initPicGv(convertView);
	}

	// /**
	// * 初始化品牌
	// */
	// private void initApplianceSpinner() {
	// Spinner spinner = (Spinner) findViewById(R.id.appliance_spinner);
	// spinner.setPrompt(getString(R.string.tag_select_hint));
	// final String[] items = getResources().getStringArray(
	// R.array.appliance_types);
	// applianceType = items[0];
	// SpinnerStringsAdapter adapter = new SpinnerStringsAdapter(this, items);
	// spinner.setAdapter(adapter);
	//
	// spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
	//
	// @Override
	// public void onItemSelected(AdapterView<?> arg0, View arg1,
	// int arg2, long arg3) {
	// applianceType = items[arg2];
	// }
	//
	// @Override
	// public void onNothingSelected(AdapterView<?> arg0) {
	//
	// }
	// });
	//
	// }

	/**
	 * 初始化选择文件
	 * 
	 * @param convertView
	 */
	private void initSelectFileLayout(View convertView) {
		findViewById(R.id.lyt_select_file).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
						intent.setType("*/*");
						intent.addCategory(Intent.CATEGORY_OPENABLE);

						try {
							startActivityForResult(Intent.createChooser(intent,
									"Select a File to Upload"),
									FILE_SELECT_CODE);
						} catch (android.content.ActivityNotFoundException ex) {
							Toast.makeText(SubmitCompetingActivity.this,
									"Please install a File Manager.",
									Toast.LENGTH_SHORT).show();
						}
					}
				});

	}

	private void initPicGv(View convertView) {
		if (backEntity != null) {
			if (backEntity.picNames.size() > 0) {
				picList.clear();
				for (String path : backEntity.picNames) {
					PhotoEntity entity = new PhotoEntity();
					entity.path = path;
					picList.add(entity);
				}
			}
			if (!"".equals(backEntity.videoPath)) {
				updateVideoList(backEntity.videoPath);
			}
		}

		GridViewIsChildOfScrollView picGv = (GridViewIsChildOfScrollView) findViewById(R.id.gv_pic);
		mAdapter = new SinglePicListAdapter(picGv,
				SubmitCompetingActivity.this, convertView, picList, mSelf);

		GridViewIsChildOfScrollView videoGv = (GridViewIsChildOfScrollView) findViewById(R.id.gv_video);
		mVideoAdapter = new SingleVideoListAdapter(videoGv,
				SubmitCompetingActivity.this, convertView, videoList, mSelf);
	}

	private void initTitleButtonBar() {
		final TextView titleTv = (TextView) findViewById(R.id.tv_title);
		titleTv.setText(getString(R.string.competing_write_title));

		final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// showExistDialog();
				finish();
			}
		});
		// final Button btnRight = (Button) findViewById(R.id.btn_right);
		// btnRight.setBackgroundResource(R.drawable.btn_feedback_history_selector);
		// btnRight.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// Intent intent = new Intent(SubmitFeedBackActivityV3.this,
		// FeedbackHistoryActivity.class);
		// startActivityForResult(intent, FROM_HISTORY);
		// }
		// });
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case PHOTO_PICKED_WITH_DATA: // 相册 图片压缩
			if (resultCode == RESULT_OK) {
				Uri uri = data.getData();
				String selectedImagePath = getPath(uri);

				if (selectedImagePath == null
						|| "".equals(selectedImagePath.trim())) {
					Toast.makeText(mSelf,
							getString(R.string.feed_back_get_image_fail),
							Toast.LENGTH_LONG).show();
					return;
				}
				//
				updatePhotoList(BitmapUtil.zipPhoto(selectedImagePath));
				// updatePhotoList(selectedImagePath);
				mAdapter.notifyDataSetChanged();
			}
			break;
		case VIDEO_PICKED_WITH_DATA:// 视频
			if (resultCode == RESULT_OK) {
				Uri uri = data.getData();
				String selectedVideoPath = getViedoPath(uri);

				if (selectedVideoPath == null
						|| "".equals(selectedVideoPath.trim())) {
					Toast.makeText(mSelf,
							getString(R.string.feed_back_get_video_fail),
							Toast.LENGTH_LONG).show();
					return;
				}
				Log.w("videoPath", "path:" + selectedVideoPath);
				File file = new File(selectedVideoPath);
				if (!file.exists() || file.length() > 50 * 1024 * 1024) {
					Toast.makeText(mSelf,
							getString(R.string.feed_back_video_length_fail),
							Toast.LENGTH_LONG).show();
					return;
				}

				updateVideoList(selectedVideoPath);
			}
			break;
		// case
		case FROM_HISTORY:// 历史记录
			if (resultCode == RESULT_OK) {
				backEntity = (FeedBackEntity) data
						.getSerializableExtra("feedbackEntity");
				if (backEntity != null) {
					DbController dbController = new DbController(this);
					List<SerieEntity> entities = dbController
							.getSerieEntityLst();
					for (SerieEntity serieEntity : entities) {
						if (serieEntity.name.equals(backEntity.seriesName)) {
							updateSeriesBtn(serieEntity);
							break;
						}
					}
					View convertView = findViewById(R.id.lyt_parent);
					initPicGv(convertView);
					final EditText topic_edit = (EditText) findViewById(R.id.title_edit);
					final EditText content_edit = (EditText) findViewById(R.id.content_edit);
					topic_edit.setText(backEntity.title);
					content_edit.setText(backEntity.content);
				}
			}

			break;
		case FILE_SELECT_CODE:
			if (resultCode == RESULT_OK) {
				// Get the Uri of the selected file
				Uri uri = data.getData();
				String path = FileCacheUtil.getPath(this, uri);
				final TextView tvSelFile = (TextView) findViewById(R.id.tv_select_file);
				if (!TextUtils.isEmpty(path)) {
					tvSelFile.setText(path);
					uploadFile = new File(path);
				} else {
					uploadFile = null;
					tvSelFile.setText(R.string.submit_feed_back_select_file);
					Toast.makeText(
							this,
							getString(R.string.submit_feed_back_select_file_fail),
							Toast.LENGTH_LONG).show();
				}
			}
			break;
		}
	}

	/**
	 * 历史记录跳转
	 */
	private void initByFeedback() {

		backEntity = (FeedBackEntity) getIntent().getSerializableExtra(
				"feedbackEntity");
		if (backEntity != null) {
			DbController dbController = new DbController(this);
			List<SerieEntity> entities = dbController.getSerieEntityLst();
			for (SerieEntity serieEntity : entities) {
				if (serieEntity.name.equals(backEntity.seriesName)) {
					updateSeriesBtn(serieEntity);
					break;
				}
			}
			View convertView = findViewById(R.id.lyt_parent);
			initPicGv(convertView);
			final EditText topic_edit = (EditText) findViewById(R.id.title_edit);
			final EditText content_edit = (EditText) findViewById(R.id.content_edit);
			topic_edit.setText(backEntity.title);
			content_edit.setText(backEntity.content);
			if (!TextUtils.isEmpty(backEntity.uploadFilePath)
					&& new File(backEntity.uploadFilePath).exists()) {
				final TextView tvSelFile = (TextView) findViewById(R.id.tv_select_file);
				tvSelFile.setText(backEntity.uploadFilePath);
			}
		}

	}

	/**
	 * 压缩图片
	 */
	private String zipPhoto(final String photoFile) {
		if (photoFile == null || photoFile.trim().length() == 0) {
			return "";
		}
		File file = new File(photoFile);
		if (!file.exists()) {
			return "";
		}
		File resFile = new File(HctConstants.DEFAULT_ROOT_PATH
				+ HctConstants.DEFAULT_IMG_STORE_PATH + file.getName());
		try {
			if (resFile.getParentFile() == null
					|| !resFile.getParentFile().exists()) {
				resFile.getParentFile().mkdirs();
			}
			if (!resFile.exists()) {
				resFile.createNewFile();
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		BitmapFactory.Options options = new BitmapFactory.Options();
		if (file.length() > 10 * 1024 * 1024) {
			options.inSampleSize = 30;
		} else if (file.length() > 6 * 1024 * 1024) {
			options.inSampleSize = 20;
		} else if (file.length() > 2 * 1024 * 1024) {
			options.inSampleSize = 10;
		} else if (file.length() > 1024 * 1024) {
			options.inSampleSize = 5;
		} else if (file.length() > 1024 * 512) {
			options.inSampleSize = 2;
		} else {
			options.inSampleSize = 1;
		}
		Bitmap bmp = BitmapFactory.decodeFile(photoFile, options);
		try {
			bmp.compress(CompressFormat.JPEG, 75, new FileOutputStream(resFile));
			// FileOutputStream fos = new FileOutputStream(resFile);
			// fos.write(baos.toByteArray());
			// fos.flush();
			// fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return resFile.getAbsolutePath();

	}

	private void updatePhotoList(String selectedImagePath) {
		PhotoEntity entity = new PhotoEntity();
		entity.path = selectedImagePath;
		entity.position = mPosition;

		if (mPosition < picList.size() && picList.size() > 0) {
			picList.set(mPosition, entity);
			if (/* mPosition != 0 && */picList.size() < 6) {
				boolean bCanAdd = true;
				for (PhotoEntity photoEntity : picList) {
					if (photoEntity.path.equals("")) {
						bCanAdd = false;
					}
				}
				if (bCanAdd) {
					picList.add(new PhotoEntity());
				}

			}

		} else {
			picList.add(entity);
		}
	}

	private void updateVideoList(String selectedVideoPath) {
		VideoEntity entity = new VideoEntity();
		entity.path = selectedVideoPath;
		videoList.clear();
		videoList.add(entity);
		mVideoAdapter.notifyDataSetChanged();
	}

	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	public String getViedoPath(Uri uri) {
		String[] projection = { MediaStore.Video.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

	}

	/**
	 * 提交文本反馈
	 * 
	 * @param personId
	 * @param seriesId
	 * @param topic
	 * @param content
	 */
	private void sub_text(final Button sub_btn, final String personId,
			final String seriesId, final String topic, final String content,
			final List<String> filepaths, final List<String> videoPathes) {
		final ProgressBar loadPb = (ProgressBar) findViewById(R.id.pb_loading);
		sub_btn.setClickable(false);
		loadPb.setVisibility(View.VISIBLE);

		MobclickAgent.onEvent(this, "Normal_feadback");
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				sub_btn.setClickable(true);
				loadPb.setVisibility(View.GONE);

				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					int points = 2;
					if ((picList != null && picList.size() > 0)
							|| (videoList != null && videoList.size() > 0)) {
						++points;
					}

					Utils.submitPoints(SubmitCompetingActivity.this, points,
							"", false);
					hctResult = (HctResult) msg.obj;
					ResultEntity entity = (ResultEntity) hctResult.data;
					if (entity.statusCode.equals("0")) {
						Toast.makeText(SubmitCompetingActivity.this,
								R.string.add_feed_sucess_hint,
								Toast.LENGTH_SHORT).show();
						setResult(RESULT_OK, getIntent());
						finish();
					} else if (!entity.statusCode.equals("0")) {

						Toast.makeText(SubmitCompetingActivity.this,
								entity.msg, Toast.LENGTH_SHORT).show();
					}
					break;

				case HctConstants.STATUS_FAILD:
					Toast.makeText(SubmitCompetingActivity.this,
							getString(R.string.net_error_hint),
							Toast.LENGTH_SHORT).show();
					break;
				}
			}
		};
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(
							SubmitCompetingActivity.this);
					HctResult result = controller.submitVieinfo(
							personId,
							seriesId,
							topic,
							content,
							filepaths,
							videoPathes,
							uploadFile == null ? "" : uploadFile
									.getAbsolutePath());
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();
	}

	@Override
	public void onBackPressed() {
		// showExistDialog();
		super.onBackPressed();
	}

	/**
	 * 显示是否保存草稿对话框
	 */
	// private void showExistDialog() {
	// final EditText topic_edit = (EditText) findViewById(R.id.title_edit);
	// final EditText content_edit = (EditText) findViewById(R.id.content_edit);
	// final String topic = topic_edit.getText().toString().trim();
	// final String content = content_edit.getText().toString().trim();
	//
	// if (mCurrentFirstEntity == null || "".equals(topic)
	// || "".equals(content)) {
	// finish();
	// return;
	// }
	// AlertDialog.Builder builder = new Builder(this);
	// builder.setTitle(getString(R.string.feedback_exist_wran_title))
	// .setMessage(getString(R.string.feedback_exist_wran_info))
	// .setPositiveButton(getString(R.string.feedback_exist_leave),
	// new DialogInterface.OnClickListener() {
	//
	// @Override
	// public void onClick(DialogInterface dialog,
	// int which) {
	// finish();
	// }
	// })
	// .setNegativeButton(getString(R.string.feedback_exist_cancel),
	// null)
	// .setNeutralButton(getString(R.string.feedback_exist_save),
	// new DialogInterface.OnClickListener() {
	//
	// @Override
	// public void onClick(DialogInterface dialog,
	// int which) {
	// boolean update = true;
	// if (backEntity == null) {
	// update = false;
	// backEntity = new FeedBackEntity();
	// }
	// SimpleDateFormat dateFormat = new SimpleDateFormat(
	// "yyyy-MM-dd HH:mm:ss");
	//
	// backEntity.answerContent = content;
	// backEntity.answerName = topic;
	// backEntity.seriesName = mCurrentFirstEntity.name;
	// backEntity.submitDate = dateFormat
	// .format(new Date());
	// if (picList != null && picList.size() > 1) {
	// StringBuffer sb = new StringBuffer();
	// for (int i = 0; i < picList.size(); i++) {
	// if (i == 0) {
	// sb.append(picList.get(i).path);
	// } else {
	// if (!"".equals(picList.get(i).path)) {
	// sb.append(
	// FeedBackEntity.PIC_FILE_SEPRATOR)
	// .append(picList.get(i).path);
	// }
	// }
	// }
	// backEntity.picPathes = sb.toString();
	// }
	// if (videoList != null && videoList.size() > 0) {
	// if (!"".equals(videoList.get(0).path)) {
	// backEntity.videoPath = videoList.get(0).path;
	// }
	// }
	// if (uploadFile != null && uploadFile.exists()) {
	// backEntity.uploadFilePath = uploadFile
	// .getAbsolutePath();
	// }
	// DBFeedbackInfoManager dbFeedbackInfoManager = new DBFeedbackInfoManager(
	// getApplicationContext());
	// if (update) {
	// dbFeedbackInfoManager.updateMsg(backEntity);
	// setResult(RESULT_OK);
	// } else {
	// dbFeedbackInfoManager.add(backEntity);
	// }
	// finish();
	// }
	// }).create().show();
	//
	// }

}
